﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using static System.String;

namespace RoAssistant.Web
{
    /// <summary>
    /// 查询web
    /// </summary>
    class FindWebMain
    {
        /// <summary>
        /// 查询web控件
        /// </summary>
        /// <param name="windowname">网页地址</param>
        public static void FindWebMainMainFunc(string windowname)
        {
            //设定webdriver
            PubArgs.NewDriver = new ChromeDriver("C:/Browser");
            //设定超时
            PubArgs.NewDriver.Manage().Timeouts().PageLoad = new TimeSpan(0, 0, 30);
            //启动页面
            PubArgs.NewDriver.Navigate().GoToUrl(windowname);
            //是否截取本页面
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("释放截取本页面,如截图本页面，请输入非exit字符：");
            string input = Console.ReadLine();
            ReadBodyElements(input);
        }

        /// <summary>
        /// 查找元素
        /// </summary>
        /// <param name="command">命令</param>
        public static void ReadBodyElements(string command)
        {
            if (command == "exit")
            {
                PubArgs.NewDriver.Quit();
                Environment.Exit(0);
            }
            else
            {
                //初始化
                PubArgs.WebElementList = new List<WebElement>();
                ChangeListToTci changeListToTci= new ChangeListToTci();

                ReadOnlyCollection<IWebElement> allWebElements = PubArgs.NewDriver.FindElements(By.XPath("/html/body/*"));
                List<string> tempList = BackTagName(allWebElements, "/html/body");

                //循环根节点元素
                for (int i = 0; i < allWebElements.Count; i++)
                {
                    FeedBackFunc(allWebElements[i], tempList[i]);
                }
                //保存成为tci文件
                //是否截取本页面
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("请输入保存名称：");
                string name = Console.ReadLine();

                //写入tci文件
                changeListToTci.CreateTempTci(PubArgs.WebElementList, name);

                //是否截取本页面
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("释放截取本页面,如截图本页面，请输入非exit字符：");
                string input = Console.ReadLine();
                //回调
                ReadBodyElements(input);
            }
        }


        /// <summary>
        /// 递归函数，不断进行递归，超出所有的元素
        /// </summary>
        /// <param name="useElement">需要递归的元素</param>
        /// <param name="taname">前缀</param>
        private static void FeedBackFunc(IWebElement useElement, string taname)
        {
            //查找子节点
            ReadOnlyCollection<IWebElement> allWebElements = useElement.FindElements(By.XPath("*"));
            List<string> tempList = BackTagName(allWebElements, taname);
            //递归查找子节点
            for (int i = 0; i < allWebElements.Count; i++)
            {
                IWebElement sigElement = allWebElements[i];
                FeedBackFunc(sigElement, tempList[i]);
            }
        }


        /* Todo 重大更新，在同一层节点内查询是否有重复的节点
         * Todo 给定ID的规则
         * id->name->text->->class->target
         * 如果什么都没有，则写入一个中文保证有字符填入
         * 
         */

        /// <summary>
        /// 对单个Eelement查询唯一值
        /// 返回TagName
        /// </summary>
        /// <param name="allElement">同层所有元素</param>
        /// <param name="panode">TagName</param>
        /// <returns></returns>
        private static List<string> BackTagName(ReadOnlyCollection<IWebElement> allElement, string panode)
        {
            //返回值
            List<string> allXpath = new List<string>();

            int i = 1;

            foreach (IWebElement sigElement in allElement)
            {
                WebElement useElement = new WebElement();

                //控件值
                string eleValue;
                //如果存在id值

                if (sigElement.GetAttribute("id") != null && sigElement.GetAttribute("id") != Empty)
                {
                    eleValue = "//" + sigElement.TagName + "[@id='" + sigElement.GetAttribute("id") + "']";
                    useElement.Id = eleValue;
                }

                //如果存在name值
                else if (sigElement.GetAttribute("name") != null && sigElement.GetAttribute("name") != Empty)
                {
                    eleValue = "//" + sigElement.TagName + "[@name='" + sigElement.GetAttribute("name") + "']";
                    useElement.Id = eleValue;
                }

                //如果id/name都不存在
                else
                {
                    string temptar = panode + "/" + sigElement.TagName;

                    if (PubArgs.NewDriver.FindElements(By.XPath(temptar)).Count > 1)
                    {
                        eleValue = temptar + "[" + i + "]";
                        i++;
                    }
                    else
                    {
                        eleValue = temptar;
                    }

                    //写入text->->class->target或中文
                }
                useElement.Value = eleValue;
                //递归查找子节点元素
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(eleValue);
                allXpath.Add(eleValue);
                useElement.Id = BackConId(eleValue);
                //写入全局变量
                PubArgs.WebElementList.Add(useElement);
            }

            return allXpath;
        }


        /// <summary>
        /// 反馈Id值
        /// </summary>
        /// <param name="elevalue"></param>
        /// <returns></returns>
        private static string BackConId(string elevalue)
        {
            //    Todo 给定ID的规则
            //    id->name->text->->class->target
            //    如果什么都没有，则写入一个中文保证有字符填入

            IWebElement sigElement = PubArgs.NewDriver.FindElement(By.XPath(elevalue));
            string temp = null;
            if (sigElement.Text != null && sigElement.Text != Empty)
            {
                temp = sigElement.Text;
            }
            else if (sigElement.GetAttribute("class") != null && sigElement.GetAttribute("class") != Empty)
            {
                temp = sigElement.GetAttribute("class");
            }
            else if (sigElement.TagName != null && sigElement.TagName != Empty)
            {
                temp = sigElement.TagName + "本元素没有完整定义，请查询后重新修改";
            }

            return temp;
        }
    }
}

